﻿using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Application.Base;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.SaveDto;
using Dora.Services.AdminUser.Entities;
using Dora.Services.AdminUser.IApplication;
using Dora.Services.AdminUser.Repository;
using Dora.Services.AdminUser.Repository.Repositorys;
using Dora.Tools.Utility;
using Dora.Tools.Utility.Const;
using Microsoft.Extensions.Logging;
using Surging.Core.Common;
using Surging.Core.CPlatform.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Application
{
    /// <summary>
    /// 广告表服务
    /// </summary>
    [ModuleName(DoraModuleName.AdminUser)]
    public class AdInfoService : DoraServiceBase, IAdInfoService
    {
        private ISugarUnitOfWork _unitOfWork;
        private readonly AdInfoRepository _repository;
        private readonly OrganizationRepository _organizationRepository;
        private readonly AdPositionRepository _adpositionRepository;
       public AdInfoService(ISugarUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _repository = new AdInfoRepository(unitOfWork);
            _organizationRepository = new OrganizationRepository(unitOfWork);
            _adpositionRepository = new AdPositionRepository(unitOfWork);
        }


        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> Create(AdInfoEntity entity)
        {
            entity.CreatedTime = DateTime.Now;
            var result = await _repository.InsertAsync(entity);
            return ResultDto<int>.Success(result.Id);
        }


        /// <summary>
        /// 根据Id获取一个实体对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AdInfoEntity> GetById(int id)
        {
            return await _repository.FirstOrDefaultAsync(id);
        }


        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<AdInfoEntity>> GetPageList(AdInfoQueryDto input)
        {
            var page = await _repository.GetPageList(input);
            return page;
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> Update(AdInfoEntity entity)
        {
            entity.UpdatedTime = DateTime.Now;
            return await _repository.UpdateAsync(entity);
        }

        /// <summary>
        /// 根据IdList获取列表
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<List<AdInfoEntity>> GetList(List<int> idList)
        {
            if (idList == null || idList.Count == 0)
            {
                return new List<AdInfoEntity>();
            }
            var list = await _repository.GetAllListAsync(it => idList.Contains(it.Id));
            return list;
        }

        /// <summary>
        /// 根据广告位Id和组织Id获取列表
        /// </summary>
        /// <returns>只返回离当前组织机构最近的组织机构的广告，如果不是当前组织机构的广告，把id改成0</returns>
        public async Task<List<AdInfoEntity>> GetListByPositionIdAndOrgId(int positionId, int orgId)
        {
            var org = await _organizationRepository.FirstOrDefaultAsync(it => it.Id == orgId);
            if (org == null)
            {
                return new List<AdInfoEntity>();
            }

            if (string.IsNullOrWhiteSpace(org.LevelPath))
            {
                return new List<AdInfoEntity>();
            }
            var orgIdList = ConvertHelper.StringToList<int>(org.LevelPath, ',');

            var list = await _repository.GetListByPositionIdAndOrgIdList(positionId, orgIdList);
            if (list?.Count > 0)
            {
                var currentList = list.Where(it => it.OrgId == orgId).ToList();
                if (currentList?.Count > 0)
                {
                    return currentList;
                }
                else
                {
                    for (int i = orgIdList.Count - 1; i >= 0; i--)
                    {
                        var parentId = orgIdList[i];
                        var parentList = list.Where(it => it.OrgId == parentId).ToList();
                        if (parentList?.Count > 0)
                        {
                            foreach (var itemParent in parentList)
                            {
                                itemParent.Id = 0;
                            }
                            return parentList;
                        }
                    }
                }
            }
            return list;
        }


        /// <summary>
        /// 批量保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> BatchSave(AdInfoBatchSaveDto input)
        {
            if (input == null || input.PositionId == 0 || input.OrgId == 0)
            {
                return ResultDto<int>.Error("参数传入错误");
            }

            var existList = await _repository.GetListByPositionIdAndOrgIdList(input.PositionId, new List<int>() { input.OrgId });
            var createList = new List<AdInfoEntity>();
            var updateList = new List<AdInfoEntity>();
            var deleteList = new List<AdInfoEntity>();
            if (existList?.Count > 0)
            {
                var existIdList = existList.Select(it => it.Id).ToList();
                deleteList = existList.Where(it => !existIdList.Contains(it.Id)).ToList();
            }

            if (input.AdInfoList?.Count > 0)
            {
                foreach (var item in input.AdInfoList)
                {
                    if (string.IsNullOrWhiteSpace(item.ImgUrl))
                    {
                        return ResultDto<int>.Error("图片不能为空");
                    }
                    if (item.Id == 0)
                    {
                        item.PositionId = input.PositionId;
                        item.OrgId = input.OrgId;
                        item.CreatedTime = DateTime.Now;
                        item.CreatedUserId = input.OpUserId;
                        item.CreatedUserName = input.OpUserName;
                        createList.Add(item);
                    }
                    else
                    {
                        item.UpdatedTime = DateTime.Now;
                        item.UpdatedUserId = input.OpUserId;
                        item.UpdatedUserName = input.OpUserName;
                        updateList.Add(item);
                    }
                }
            }
            var result = 0;
            if (createList.Count > 0)
            {
                result += await _repository.BatchCreate(createList);
            }
            if (updateList.Count > 0)
            {
                result += await _repository.BatchUpdate(updateList);
            }
            if (deleteList.Count > 0)
            {
                result += await _repository.BatchDelete(deleteList);
            }
            return ResultDto<int>.Success(1);
        }

        /// <summary>
        /// 初始化大社广告位
        /// </summary>
        /// <param name="orgId">大社组织结构ID</param>
        /// <returns></returns>
        public async Task<ResultDto<int>> InitAdInfo(AdInfoBatchSaveDto input)
        {
            if (input.OrgId > 0)
            {
                var OldAdInfo = 0;
                //验证该组织机构下是否存在广告位
                OldAdInfo = await _repository.ExistAdInfoByOrgId(input.OrgId);
                if (OldAdInfo > 0)
                {
                    return ResultDto<int>.Error("无需重复初始化广告位");
                }

                var InsertAdInfoCount = 0;

                //加载广告位类型
                var AdPositionList = await _adpositionRepository.GetAll();
                var createList = new List<AdInfoEntity>();//广告位集合
                foreach (var item in AdPositionList)
                {
                    for (int i = 0; i < 4; i++)
                    {
                        var createInfo = new AdInfoEntity();
                        createInfo.OrgId = input.OrgId;
                        createInfo.Name = string.Empty;
                        createInfo.ImgUrl = string.Empty;
                        createInfo.LinkUrl = string.Empty;
                        createInfo.Sort = 99;
                        createInfo.IsShow = 1;
                        createInfo.CreatedTime = DateTime.Now;
                        createInfo.CreatedUserId = input.OpUserId;
                        createInfo.CreatedUserName = input.OpUserName;
                        createInfo.PositionId = item.Id;
                        createInfo.LinkType = 0;
                        createList.Add(createInfo);
                        InsertAdInfoCount++;
                    }
                }

                var result = 0;
                if (InsertAdInfoCount>0)
                {
                    result = await _repository.BatchCreate(createList);
                }
                if (result == 0)
                {
                    return ResultDto<int>.Error("初始化失败");
                }
                else
                {
                    return ResultDto<int>.Success("初始化广告位成功",result);
                }

            }
            else
            {
                return ResultDto<int>.Error("获取大社组织机构代码失败,请校验");
            }
        }
    }
}
